package routers

import (
	"net/http"
	"punch/dbs"
	"strconv"

	"github.com/gin-gonic/gin"
)

func LoadOrg(e *gin.Engine) {
	e.POST("/punc/org/add", orgAddHandler)
	e.POST("/punc/org/delete", orgDeleteHandler)
	e.POST("/punc/org/edit", orgEditHandler)
	e.POST("/punc/org/get", orgGetHandler)
}

// 定义数据表结构体
type Org struct {
	Id          int    `db:"id"`
	Par_id      int    `db:"par_id"`
	Name        string `db:"name"`
	Note        string `db:"note"`
	Create_time string `db:"create_time"`
	Update_time string `db:"update_time"`
}

// 添加数据结构体
type OrgParamsAdd struct {
	Name string `json:"name" binding:"required"`
	Note string `json:"note" binding:"required"`
}

// 删除数据结构体
type OrgParamsDelete struct {
	Id int `json:"id" binding:"required"`
}

// 编辑数据结构体
type OrgParamsEdit struct {
	Id   int    `json:"id" binding:"required"`
	Name string `json:"name" binding:"required"`
	Note string `json:"note" binding:"required"`
}

// 查询数据结构体
type OrgParamsGet struct {
	PageNo   int    `json:"pageNo"`
	PageSize int    `json:"pageSize"`
	Id       int    `json:"id"`
	Name     string `json:"name"`
}

func orgAddHandler(c *gin.Context) {
	if tempUserType, _ := c.Get("Usertype"); tempUserType != "manager" {
		c.JSON(http.StatusOK, gin.H{
			"code": 20020,
			"msg":  "权限不足",
		})
		return
	}
	var params OrgParamsAdd
	if err := c.ShouldBindJSON(&params); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20003,
			"msg":  err.Error(),
		})
		return
	}

	db, err := dbs.Conn(c)
	if err != nil {
		db.Close()
		return
	}

	var org []Org
	err = db.Select(&org, "select id from org where name=?", params.Name)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20004,
			"msg":  err.Error(),
		})
		return
	}
	if len(org) != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 20010,
			"msg":  "已存在该机构",
		})
		return
	}

	r, err := db.Exec("insert into org(name, note) values(?, ?)",
		params.Name, params.Note)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20004,
			"msg":  err.Error(),
		})
		return
	}
	id, err := r.LastInsertId()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20000,
			"msg":  err.Error(),
		})
		return
	}

	err = db.Select(&org, "select * from org where id=?", id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20000,
			"msg":  err.Error(),
		})
		return
	}
	if len(org) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 20000,
			"msg":  "添加成功",
			"data": gin.H{
				"Id": id,
			},
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"msg":  "添加成功",
		"data": gin.H{
			"Id":          id,
			"Par_id":      org[0].Par_id,
			"Name":        org[0].Name,
			"Note":        org[0].Name,
			"Create_time": org[0].Create_time,
			"Update_time": org[0].Update_time,
		},
	})

	db.Close()
}

func orgDeleteHandler(c *gin.Context) {
	if tempUserType, _ := c.Get("Usertype"); tempUserType != "manager" {
		c.JSON(http.StatusOK, gin.H{
			"code": 20020,
			"msg":  "权限不足",
		})
		return
	}
	var params OrgParamsDelete
	if err := c.ShouldBindJSON(&params); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20003,
			"msg":  err.Error(),
		})
		return
	}

	db, err := dbs.Conn(c)
	if err != nil {
		db.Close()
		return
	}

	_, err = db.Exec("delete from org where id=?", params.Id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20004,
			"msg":  err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"msg":  "删除成功",
		"data": gin.H{
			"Id": params.Id,
		},
	})

	db.Close()
}

func orgEditHandler(c *gin.Context) {
	if tempUserType, _ := c.Get("Usertype"); tempUserType != "manager" {
		c.JSON(http.StatusOK, gin.H{
			"code": 20020,
			"msg":  "权限不足",
		})
		return
	}

	var params OrgParamsEdit
	if err := c.ShouldBindJSON(&params); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20003,
			"msg":  err.Error(),
		})
		return
	}

	db, err := dbs.Conn(c)
	if err != nil {
		db.Close()
		return
	}

	var org1 []Org
	err = db.Select(&org1, "select id from org where name=?", params.Name)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20023,
			"msg":  err.Error(),
		})
		return
	}
	if len(org1) > 1 {
		c.JSON(http.StatusOK, gin.H{
			"code": 20031,
			"msg":  "已存在此机构，请更换其他名称",
			"data": gin.H{
				"Id":   params.Id,
				"Name": params.Name,
			},
		})
		return
	}

	var org []Org
	err = db.Select(&org, "select * from org where id=?", params.Id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20023,
			"msg":  err.Error(),
		})
		return
	}
	if len(org) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 20030,
			"msg":  "无此机构",
			"data": gin.H{
				"Id": params.Id,
			},
		})
		return
	}
	org[0].Name = params.Name
	org[0].Note = params.Note

	_, err = db.Exec("update org set name=?, note=? where id=?", org[0].Name, org[0].Note, params.Id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20025,
			"msg":  err.Error(),
		})
		return
	}

	var org2 []Org
	err = db.Select(&org2, "select * from org where id=?", params.Id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20023,
			"msg":  err.Error(),
		})
		return
	}
	if len(org2) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 20025,
			"msg":  "无此机构",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"msg":  "更新成功",
		"data": gin.H{
			"Id":          org2[0].Id,
			"Par_id":      org2[0].Par_id,
			"Name":        org2[0].Name,
			"Note":        org2[0].Note,
			"Create_time": org2[0].Create_time,
			"Update_time": org2[0].Update_time,
		},
	})

	db.Close()
}

func orgGetHandler(c *gin.Context) {
	if tempUserType, _ := c.Get("Usertype"); tempUserType != "manager" {
		c.JSON(http.StatusOK, gin.H{
			"code": 20020,
			"msg":  "权限不足",
		})
		return
	}

	var params OrgParamsGet
	if err := c.ShouldBindJSON(&params); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20003,
			"msg":  err.Error(),
		})
		return
	}

	db, err := dbs.Conn(c)
	if err != nil {
		db.Close()
		return
	}

	tempSql := "select id, par_id, name, note, create_time, update_time from org"
	hasAnd := " where"
	if params.Id != 0 {
		tempSql = tempSql + hasAnd + " id=" + strconv.Itoa(params.Id)
		hasAnd = " and"
	}
	if params.Name != "" {
		tempSql = tempSql + hasAnd + " name like '%" + params.Name + "%'"
		hasAnd = " and"
	}
	tempSql = tempSql + " order by create_time desc"
	if params.PageNo != 0 && params.PageSize != 0 {
		tempSql = tempSql + " limit " + strconv.Itoa((params.PageNo-1)*params.PageSize) + "," + strconv.Itoa(params.PageSize)
	}

	var org []Org
	err = db.Select(&org, tempSql)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20004,
			"msg":  err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"msg":  "查询成功",
		"data": org,
	})

	db.Close()
}
